//
//  ViewController.m
//  PageSlideDemo
//
//  Created by guopanpan on 13-6-26.
//  Copyright (c) 2013年 guopanpan. All rights reserved.
//

#import "ViewController.h"
#import "SubViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    NSMutableArray *controllers = [[NSMutableArray alloc] init];
    
    for (unsigned i = 0; i < 7; i++) {
        [controllers addObject:[NSNull null]];
    }
    
    viewControllers = controllers;
    
    scrollView.pagingEnabled = YES;
    
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 7,
                                        scrollView.frame.size.height);
    
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    
    scrollView.scrollsToTop = NO;
    scrollView.delegate = self;
    
    pageControl.numberOfPages = 7;
    pageControl.currentPage = 0;
    [self loadScrollViewWithPage:0];
    [self loadScrollViewWithPage:1];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadScrollViewWithPage:(int)page
{
    if (page < 0) {
        return;
    }
    if (page >= 7) {
        return;
    }
    
    SubViewController *controller = [viewControllers objectAtIndex:page];
    
    
    if ((NSNull *)controller == [NSNull null]) {
        controller = [[SubViewController alloc] initwithPageNumber:page];
        [viewControllers replaceObjectAtIndex:page withObject:controller];
        
    }
    
    
    
    if (nil == controller.view.superview) {
        CGRect frame = scrollView.frame;
        
        frame.origin.x = frame.size.width * page;
        
        frame.origin.y = 0;
        
        controller.view.frame = frame;
        
        [scrollView addSubview:controller.view];
        
        
        
    }
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    NSLog(@"111 %f", scrollView.contentOffset.x);
    
    if (pageControlUsed) {
        return;
    }
    
    CGFloat pageWidth = scrollView.frame.size.width;
    
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
    
    [self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    
    [self loadScrollViewWithPage:page + 1];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    pageControlUsed = NO;
}















@end
